package com.cxy.ch1.vola;

/**
 * @ClassName: NotSafe
 * @Description: TODO(线程不安全)
 * @author 菜徐鸭
 * @date 2020年4月13日
 *
 */
public class NotSafe {
	private volatile long count = 0;

	public long getCount() {
		return count;
	}

	public void setCount(long count) {
		this.count = count;
	}

	// count进行累加
	public void incCount() {
		count++;
	}

	// 线程
	private static class Count extends Thread {

		private NotSafe simplOper;

		public Count(NotSafe simplOper) {
			this.simplOper = simplOper;
		}

		@Override
		public void run() {
			for (int i = 0; i < 10000; i++) {
				simplOper.incCount();
			}
		}
	}

	/**
	 *  volatile：可见性，但是不能保证原子，适合一写多读（一个线程写）的场景
	 * @param args
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws InterruptedException {
		NotSafe simplOper = new NotSafe();
		// 启动两个线程
		Count count1 = new Count(simplOper);
		Count count2 = new Count(simplOper);
		count1.start();
		count2.start();
		Thread.sleep(50);
		System.out.println(simplOper.count);// 20000?
	}
}
